# -*- coding: utf-8 -*-
import logging
from traceback import format_exc
from scrapy import signals
from zc_core.dao.batch_dao import BatchDao
from zc_core.dao.sku_pool_dao import SkuPoolDao
from zc_core.dao.spu_pool_dao import SpuPoolDao

logger = logging.getLogger(__name__)


class BatchMonitorExtension(object):

    def __init__(self):
        super()
        self.batch_dao = BatchDao()
        self.sku_pool_dao = SkuPoolDao()
        self.spu_pool_dao = SpuPoolDao()

    @classmethod
    def from_crawler(cls, crawler):
        ext = cls()
        # crawler.signals.connect(ext.spider_opened, signal=signals.spider_opened)
        crawler.signals.connect(ext.spider_closed, signal=signals.spider_closed)
        return ext

    def spider_closed(self, spider):
        # 记录批次完成状态
        try:
            if spider.name and (spider.name in ['full', 'part'] or 'full' in spider.name):
                if spider.batch_no:
                    batch_no = spider.batch_no
                    self.batch_dao.update_batch(batch_no, status=2)
                    spider.logger.info("close full spider %s with batch %s" % (spider.name, batch_no))
                else:
                    spider.logger.info("close full spider %s without update batch ...", spider.name)
            if spider.name and spider.name == 'sku':
                if spider.batch_no:
                    batch_no = spider.batch_no
                    # 更新商品池
                    self.update_sku_pool(batch_no)
                    spider.logger.info("close sku pool spider %s with batch %s" % (spider.name, batch_no))
                else:
                    spider.logger.info("close sku spider %s without update pool ...", spider.name)
            if spider.name and spider.name == 'spu':
                if spider.batch_no:
                    batch_no = spider.batch_no
                    # 更新商品池
                    self.update_spu_pool(batch_no)
                    spider.logger.info("close spu pool spider %s with batch %s" % (spider.name, batch_no))
                else:
                    spider.logger.info("close spu spider %s without update pool ...", spider.name)
        except Exception as e:
            _ = e
            spider.logger.error(format_exc())

    # 更新批次信息
    def update_sku_pool(self, batch_no):
        # 更新下线商品
        result = self.sku_pool_dao.update_offline(batch_no)
        logger.info("update offline items [%s] in batch [%s]" % (result, batch_no))

    # 更新批次信息
    def update_spu_pool(self, batch_no):
        # 更新下线商品
        result = self.spu_pool_dao.update_offline(batch_no)
        logger.info("update offline items [%s] in batch [%s]" % (result, batch_no))
